<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>插件管理 - AegisX</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
            min-height: 100vh;
        }
        
        .plugin-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .plugin-management-header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }
        
        .plugin-management-header h2 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        
        .plugin-management-header p {
            font-size: 1.2rem;
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .plugin-toolbar {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .toolbar-left {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .toolbar-right {
            display: flex;
            align-items: center;
        }
        
        .search-box {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .search-box input {
            border-radius: 8px;
            border: 1px solid #dee2e6;
            padding: 8px 12px;
            width: 200px;
        }
        
        .plugin-stats-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            gap: 15px;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
        }
        
        .stat-icon {
            font-size: 2rem;
            color: #007bff;
            width: 50px;
            text-align: center;
        }
        
        .stat-info {
            flex: 1;
        }
        
        .stat-number {
            font-size: 1.8rem;
            font-weight: 700;
            color: #495057;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .plugin-list-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 25px;
        }
        
        .plugin-list-container h3 {
            color: #495057;
            margin-bottom: 20px;
            font-size: 1.4rem;
            font-weight: 600;
        }
        
        .plugin-list-container h3 i {
            margin-right: 10px;
            color: #007bff;
        }
        
        .plugin-list {
            display: grid;
            gap: 15px;
        }
        
        .plugin-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #007bff;
            transition: all 0.3s ease;
        }
        
        .plugin-item:hover {
            transform: translateX(5px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .plugin-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .plugin-name {
            font-size: 1.2rem;
            font-weight: 600;
            color: #495057;
        }
        
        .plugin-version {
            background: #e9ecef;
            color: #6c757d;
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .plugin-description {
            color: #6c757d;
            margin-bottom: 15px;
            font-size: 0.95rem;
        }
        
        .plugin-actions {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-running {
            background-color: #28a745;
            box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
        }
        
        .status-stopped {
            background-color: #dc3545;
            box-shadow: 0 0 10px rgba(220, 53, 69, 0.5);
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
            font-style: italic;
        }
        
        .loading::after {
            content: '';
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #6c757d;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background: white;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease;
        }
        
        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .modal-header {
            padding: 20px 25px;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h3 {
            margin: 0;
            color: #495057;
            font-size: 1.3rem;
            font-weight: 600;
        }
        
        .modal-header h3 i {
            margin-right: 10px;
            color: #007bff;
        }
        
        .close {
            font-size: 1.5rem;
            cursor: pointer;
            color: #6c757d;
            transition: color 0.3s ease;
        }
        
        .close:hover {
            color: #dc3545;
        }
        
        .modal-body {
            padding: 25px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #495057;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            font-size: 0.95rem;
            transition: border-color 0.3s ease;
        }
        
        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 25px;
        }
        
        @media (max-width: 768px) {
            .plugin-toolbar {
                flex-direction: column;
                align-items: stretch;
            }
            
            .toolbar-left,
            .toolbar-right {
                justify-content: center;
            }
            
            .search-box input {
                width: 100%;
            }
            
            .plugin-stats-overview {
                grid-template-columns: 1fr;
            }
            
            .plugin-actions {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="plugin-container">
        <div class="plugin-management-header">
            <h2><i class="bi bi-plugin"></i> 插件管理中心</h2>
            <p>管理和配置您的插件生态系统</p>
        </div>
        
        <!-- 插件操作工具栏 -->
        <div class="plugin-toolbar">
            <div class="toolbar-left">
                <button class="btn btn-success" onclick="refreshPlugins()"><i class="bi bi-arrow-clockwise"></i> 刷新列表</button>
                <button class="btn btn-primary" onclick="showUploadModal()"><i class="bi bi-upload"></i> 上传插件</button>
                <button class="btn btn-info" onclick="loadPluginStats()"><i class="bi bi-bar-chart"></i> 统计信息</button>
            </div>
            <div class="toolbar-right">
                <div class="search-box">
                    <input type="text" id="pluginSearch" placeholder="搜索插件..." onkeyup="filterPlugins()">
                    <button class="btn btn-secondary" onclick="filterPlugins()"><i class="bi bi-search"></i></button>
                </div>
            </div>
        </div>
        
        <!-- 插件统计概览 -->
        <div class="plugin-stats-overview">
            <div class="stat-card">
                <div class="stat-icon"><i class="bi bi-box"></i></div>
                <div class="stat-info">
                    <div class="stat-number" id="totalPlugins">-</div>
                    <div class="stat-label">总插件数</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="bi bi-check-circle"></i></div>
                <div class="stat-info">
                    <div class="stat-number" id="activePlugins">-</div>
                    <div class="stat-label">已启用</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="bi bi-pause-circle"></i></div>
                <div class="stat-info">
                    <div class="stat-number" id="stoppedPlugins">-</div>
                    <div class="stat-label">已停用</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="bi bi-exclamation-triangle"></i></div>
                <div class="stat-info">
                    <div class="stat-number" id="errorPlugins">-</div>
                    <div class="stat-label">异常</div>
                </div>
            </div>
        </div>
        
        <!-- 插件列表 -->
        <div class="plugin-list-container">
            <h3><i class="bi bi-list-ul"></i> 插件列表</h3>
            <div id="pluginList" class="plugin-list">
                <div class="loading">正在加载插件列表...</div>
            </div>
        </div>
        
        <!-- 上传插件模态框 -->
        <div id="uploadModal" class="modal" style="display: none;">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="bi bi-upload"></i> 上传新插件</h3>
                    <span class="close" onclick="hideUploadModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="pluginUploadForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="pluginFile">选择插件文件 (.jar):</label>
                            <input type="file" id="pluginFile" name="file" accept=".jar" required>
                        </div>
                        <div class="form-group">
                            <label for="pluginDescription">插件描述 (可选):</label>
                            <textarea id="pluginDescription" name="description" rows="3" placeholder="请输入插件描述..."></textarea>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary" onclick="hideUploadModal()">取消</button>
                            <button type="submit" class="btn btn-primary">上传插件</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 通用错误处理函数
        function handleError(error, container, defaultMessage = '操作失败') {
            const message = error.message || defaultMessage;
            if (container) {
                container.innerHTML = `<div class="alert alert-danger">${message}</div>`;
            } else {
                alert(message);
            }
        }
        
        // 通用API调用函数
        async function apiCall(url, options = {}) {
            try {
                const response = await fetch(url, options);
                return await response.json();
            } catch (error) {
                throw new Error(`网络错误: ${error.message}`);
            }
        }
        
        // 加载插件统计数据
        async function loadPluginStats() {
            const totalPlugins = document.getElementById('totalPlugins');
            const activePlugins = document.getElementById('activePlugins');
            const stoppedPlugins = document.getElementById('stoppedPlugins');
            const errorPlugins = document.getElementById('errorPlugins');

            try {
                const result = await apiCall('/api/plugins/stats');
                if (result.code === 200) {
                    const stats = result.data;
                    if (totalPlugins) totalPlugins.textContent = stats.totalPlugins || 0;
                    if (activePlugins) activePlugins.textContent = stats.startedPlugins || 0;
                    if (stoppedPlugins) stoppedPlugins.textContent = stats.stoppedPlugins || 0;
                    if (errorPlugins) errorPlugins.textContent = stats.failedPlugins || 0;
                } else {
                    console.error("Failed to load plugin stats:", result.message);
                    // 显示错误状态
                    if (totalPlugins) totalPlugins.textContent = '-';
                    if (activePlugins) activePlugins.textContent = '-';
                    if (stoppedPlugins) stoppedPlugins.textContent = '-';
                    if (errorPlugins) errorPlugins.textContent = '-';
                }
            } catch (error) {
                console.error("Error loading plugin stats:", error);
                // 显示错误状态
                if (totalPlugins) totalPlugins.textContent = '-';
                if (activePlugins) activePlugins.textContent = '-';
                if (stoppedPlugins) stoppedPlugins.textContent = '-';
                if (errorPlugins) errorPlugins.textContent = '-';
            }
        }
        
        // 加载插件数据
        async function loadPluginData() {
            const pluginList = document.getElementById('pluginList');
            if (!pluginList) return;
            pluginList.innerHTML = '<div class="loading">正在加载插件列表...</div>';
            
            try {
                const result = await apiCall('/api/plugins');
                if (result.code === 200) {
                    const data = result.data;
                    const plugins = data.plugins || [];
                    let html = '';
                    
                    plugins.forEach(plugin => {
                        // 默认状态为已停止，因为API只返回基本信息
                        const statusClass = 'status-stopped';
                        const statusText = '已停止';
                        const actionBtn = `<button class="btn btn-success btn-sm" onclick="startPlugin('${plugin.name}')">启动</button>`;
                        
                        html += `
                            <div class="plugin-item">
                                <div class="plugin-header">
                                    <div class="plugin-name">${plugin.name || '未知插件'}</div>
                                    <div class="plugin-version">v${plugin.version || '1.0.0'}</div>
                                </div>
                                <div class="plugin-description">${plugin.description || '暂无描述'}</div>
                                <div class="plugin-actions">
                                    <span class="status-indicator ${statusClass}"></span>
                                    <span>${statusText}</span>
                                    ${actionBtn}
                                    <button class="btn btn-info btn-sm" onclick="configPlugin('${plugin.name}')">配置</button>
                                    <button class="btn btn-danger btn-sm" onclick="uninstallPlugin('${plugin.name}')">卸载</button>
                                </div>
                            </div>
                        `;
                    });
                    
                    pluginList.innerHTML = html || '<div class="no-plugins">暂无插件</div>';
                } else {
                    console.error('Failed to load plugins:', result.message);
                    pluginList.innerHTML = '<div class="error">加载插件列表失败: ' + (result.message || '未知错误') + '</div>';
                }
            } catch (error) {
                console.error("Error loading plugin data:", error);
                pluginList.innerHTML = '<div class="error">加载插件列表失败</div>';
            }
        }
        
        // 插件管理功能
        function refreshPlugins() {
            loadPluginData();
            loadPluginStats();
        }
        
        function showUploadModal() {
            document.getElementById('uploadModal').style.display = 'flex';
        }
        
        function hideUploadModal() {
            document.getElementById('uploadModal').style.display = 'none';
        }
        
        function filterPlugins() {
            const searchTerm = document.getElementById('pluginSearch').value.toLowerCase();
            const pluginItems = document.querySelectorAll('.plugin-item');
            
            pluginItems.forEach(item => {
                const pluginName = item.querySelector('.plugin-name').textContent.toLowerCase();
                const pluginDesc = item.querySelector('.plugin-description').textContent.toLowerCase();
                
                if (pluginName.includes(searchTerm) || pluginDesc.includes(searchTerm)) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        }
        
        function startPlugin(pluginName) {
            alert(`启动插件: ${pluginName}`);
            // 这里可以添加实际的启动插件API调用
            setTimeout(() => {
                refreshPlugins();
                // 广播插件状态变化
                broadcastPluginStatusChange(pluginName, 'start', 'running');
            }, 500);
        }
        
        function stopPlugin(pluginName) {
            alert(`停止插件: ${pluginName}`);
            // 这里可以添加实际的停止插件API调用
            setTimeout(() => {
                refreshPlugins();
                // 广播插件状态变化
                broadcastPluginStatusChange(pluginName, 'stop', 'stopped');
            }, 500);
        }
        
        function configPlugin(pluginName) {
            alert(`配置插件: ${pluginName}`);
            // 这里可以添加实际的配置插件功能
            // 广播插件配置变化
            broadcastPluginStatusChange(pluginName, 'config', 'configured');
        }
        
        function uninstallPlugin(pluginName) {
            if (confirm(`确定要卸载插件 "${pluginName}" 吗？`)) {
                alert(`卸载插件: ${pluginName}`);
                // 这里可以添加实际的卸载插件API调用
                setTimeout(() => {
                    refreshPlugins();
                    // 广播插件状态变化
                    broadcastPluginStatusChange(pluginName, 'uninstall', 'uninstalled');
                }, 500);
            }
        }
        
        // iframe通信功能
        function sendMessageToParent(action, data) {
            if (window.parent && window.parent !== window) {
                window.parent.postMessage({
                    type: 'IFRAME_MESSAGE',
                    source: 'plugin-management',
                    action: action,
                    data: data
                }, '*');
            }
        }
        
        // 监听来自父页面的消息
        window.addEventListener('message', function(event) {
            if (event.origin !== window.location.origin) {
                return;
            }
            
            const message = event.data;
            if (message && message.type === 'PARENT_MESSAGE' && message.target === 'plugin-management') {
                handleParentMessage(message.data);
            } else if (message && message.type === 'BROADCAST') {
                handleBroadcastMessage(message);
            }
        });
        
        // 处理来自父页面的消息
        function handleParentMessage(data) {
            if (data.action === 'REFRESH') {
                loadPluginStats();
                loadPluginData();
            } else if (data.action === 'UPDATE_THEME') {
                // 处理主题更新
                document.body.className = data.theme || '';
            }
        }
        
        // 处理广播消息
        function handleBroadcastMessage(message) {
            // 可以处理来自其他iframe的消息
            console.log('收到广播消息:', message);
        }
        
        // 广播插件状态变化
        function broadcastPluginStatusChange(pluginId, action, status) {
            sendMessageToParent('BROADCAST', {
                type: 'PLUGIN_STATUS_CHANGED',
                pluginId: pluginId,
                action: action,
                status: status,
                timestamp: new Date().toISOString()
            });
        }
        
        // 表单提交处理
        document.addEventListener('DOMContentLoaded', function() {
            // 加载初始数据
            loadPluginData();
            loadPluginStats();
            
            // 通知父页面插件管理页面已加载
            sendMessageToParent('SHOW_NOTIFICATION', {
                message: '插件管理页面加载完成',
                type: 'success'
            });
            
            // 上传表单处理
            const uploadForm = document.getElementById('pluginUploadForm');
            if (uploadForm) {
                uploadForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    const submitButton = this.querySelector('button[type="submit"]');
                    
                    // 显示加载状态
                    submitButton.disabled = true;
                    submitButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 上传中...';
                    
                    // 模拟上传过程
                    setTimeout(() => {
                        alert('插件上传成功！');
                        hideUploadModal();
                        this.reset();
                        refreshPlugins();
                        
                        // 恢复按钮状态
                        submitButton.disabled = false;
                        submitButton.innerHTML = '上传插件';
                    }, 2000);
                });
            }
        });
    </script>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>